#include "../include/graphics.h"
#include "../include/object.h"

void ggInit()
{
	SDL_Init(SDL_INIT_EVERYTHING);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_SetVideoMode(
			SDL_GetVideoInfo()->current_w,
			SDL_GetVideoInfo()->current_h,
			SDL_GetVideoInfo()->vfmt->BitsPerPixel,
			SDL_OPENGL | SDL_FULLSCREEN | SDL_DOUBLEBUF);

	SDL_EnableKeyRepeat(10, 10);
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glEnable(GL_ALPHA_TEST);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);

	ilInit ();
	iluInit();
	ilutInit();
	return;
}

GLuint ggLoadTexture(const char *fileName)
{
	ILuint imageName = 0;
	GLuint textureID;
	ilGenImages(1, &imageName);
	ilBindImage(imageName);
	ilLoadImage(fileName);

	ilutRenderer(ILUT_OPENGL);
	textureID = ilutGLBindTexImage();
	ilDeleteImages(1, &imageName);
	return textureID;
}

static void ggRenderObject(hObject object_handler)
{
	pImage image_info = getImage(object_handler);
	pObject object = getData(object_handler);
	GLfloat vertexes[4][5] = {
			{
					image_info->pos.x,
					image_info->pos.y,
					object->pos.x,
					object->pos.y,
					0.f
			},
			{
					image_info->pos.x + image_info->size.x,
					image_info->pos.y,
					object->pos.x + object->size.x,
					object->pos.y,
					0.f
			},
			{
					image_info->pos.x + image_info->size.x,
					image_info->pos.y + image_info->size.y,
					object->pos.x + object->size.x,
					object->pos.y + object->size.y,
					0.f
			},
			{
					image_info->pos.x,
					image_info->pos.y + image_info->size.y,
					object->pos.x,
					object->pos.y + object->size.y,
					0.f
			}
	};
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBindTexture(GL_TEXTURE_2D, image_info->texture);
	glInterleavedArrays(GL_T2F_V3F, 0, vertexes);
	glDrawArrays(GL_QUADS, 0, 4);
	return;
}

void ggDisplay()
{
	iObjectIterator iter;
	hObject object;
	int player_id;
	int digit;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	for (object = firstObject(&iter); object; object = nextObject(&iter))
	{
		ggRenderObject(object);
	}

	for (player_id = 0; player_id < getPlayerCount(); player_id++)
		ggRenderObject(getPlayer(player_id));

	for(player_id = 0; player_id < getPlayerCount(); player_id++)
		for(digit = 0; digit < MAX_DIGITS; digit++)
		{
			updateScoreBoard(player_id, getData(getPlayer(player_id))->hp);
			ggRenderObject(getScoreBoard(player_id, digit));
		}

	SDL_GL_SwapBuffers();
	return;
}
